package com.dacool.fragment;

import java.util.ArrayList;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.dialog.BasePickerDialog.PickerDialogDelegate;
import com.dacool.dialog.ChoosePayMethodDialog;
import com.dacool.helper.DaCoolHelper;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.CalculateFeeRequest;
import com.dacool.http.CreateOrderRequest;
import com.dacool.model.CartItem;
import com.dacool.model.DCAddress;
import com.dacool.model.DCUser;
import com.dacool.model.DaCoolTransactionBill;
import com.dacool.util.ViewUtils;
import com.dacool.view.holder.CartItemCell;

public class OrderFragment extends BaseFragment implements OnClickListener {

	private ArrayList<CartItem> orderItems = new ArrayList<CartItem>();

	private LinearLayout itemContainer;
	private ViewHolder userInfoContainer;
	private ViewHolder payMethodContainer;
	private ViewHolder coolbDiscountContainer;
//	private ViewHolder couponDiscountContainer;

	private TextView totalPriceLabel;
	private TextView deliverFeeLabel;
	private TextView discountLabel;
	private TextView discountedPriceLabel;
	private Button confirmButton;

	private double totalPrice = 0;
	private int selectedPayMethod = 0;
	private int selectedDistrict = 0;

	public ArrayList<CartItem> getOrderItems() {
		return new ArrayList<CartItem>(this.orderItems);
	}

	public void setOrderItems(ArrayList<CartItem> orderItems) {
		this.orderItems = new ArrayList<CartItem>(orderItems);
	}

	// @Override
	// protected boolean showDefaultLeftButton() {
	// return true;
	// }

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_order_submit;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	private class ViewHolder {
		private View container;
		private TextView configurableTextView1;
		private TextView configurableTextView2;
		private EditText textInput;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);

		itemContainer = ViewUtils.findViewById(view, R.id.itemContainer);

		userInfoContainer = new ViewHolder();
		userInfoContainer.container = ViewUtils.findViewById(view,
				R.id.userInfoContainer);
		userInfoContainer.configurableTextView1 = ViewUtils.findViewById(view,
				R.id.userInfo_name);
		userInfoContainer.configurableTextView2 = ViewUtils.findViewById(view,
				R.id.userInfo_address);
		userInfoContainer.container.setOnClickListener(this);

		payMethodContainer = new ViewHolder();
		payMethodContainer.container = ViewUtils.findViewById(view,
				R.id.purchMethodContainer);
		payMethodContainer.configurableTextView1 = ViewUtils.findViewById(view,
				R.id.payInfo_method);

		payMethodContainer.container.setOnClickListener(this);

		coolbDiscountContainer = new ViewHolder();
		coolbDiscountContainer.container = ViewUtils.findViewById(view,
				R.id.coolbDiscountContainer);
		coolbDiscountContainer.configurableTextView1 = ViewUtils.findViewById(
				view, R.id.coolbdiscountLabel);
		coolbDiscountContainer.textInput = ViewUtils.findViewById(view,
				R.id.coolbInput);

//		couponDiscountContainer = new ViewHolder();
//		couponDiscountContainer.container = ViewUtils.findViewById(view,
//				R.id.couponContainer);

		totalPriceLabel = ViewUtils.findViewById(view, R.id.priceLabel);
		deliverFeeLabel = ViewUtils.findViewById(view, R.id.deliverFeeLabel);
		discountedPriceLabel = ViewUtils.findViewById(view,
				R.id.calculatedPriceLabel);
		discountLabel = ViewUtils.findViewById(view, R.id.coolbdiscountLabel);
		confirmButton = ViewUtils.findViewById(view, R.id.confirmOrderButton);

		confirmButton.setOnClickListener(this);

	}

	@Override
	public void onResume() {
		super.onResume();
		totalPrice = 0;
		itemContainer.removeAllViews();
		for (CartItem item : this.orderItems) {
			View itemView = CartItemCell.createFromInflator(LayoutInflater
					.from(getActivity()));
			CartItemCell cell = (CartItemCell) itemView.getTag();
			if (item.getProduct().getIconUrl() != null
					&& item.getProduct().getIconUrl().length() > 0) {
				ViewUtils.bmUtils.display(cell.iconView, item.getProduct()
						.getIconUrl());
			} else
				cell.iconView.setImageResource(R.drawable.bannerimg);
			cell.titleLabel.setText(item.getProduct().getName());
			cell.priceLabel.setText(String.format("%d x %.2f",
					item.getAmount(), item.getProduct().getPrice()));
			totalPrice += item.getAmount() * item.getProduct().getPrice();
			int index = itemContainer.getChildCount() - 1;
			itemView.setTag(null);
			itemView.setBackgroundResource(R.drawable.graybg);
			LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);
			itemContainer.addView(itemView, index, lp);

		}
		double fee = 0;
		if (DCUser.sharedUser().address != null) {
			DCAddress address = DCUser.sharedUser().address;
			userInfoContainer.configurableTextView1.setText(String.format(
					"%s %s", address.deliveryMan, address.mobileNo));
			userInfoContainer.configurableTextView2.setText(String.format(
					"%s %s", address.area, address.address));
			// fee = address.extraTransFeeNeeded ? 10 : 0;
			new CalculateFeeRequest().setAddressId(address.id)
					.setGoodsList(orderItems).setShippingId(1)
					.setHandler(new ResponseHandler() {

						@Override
						public void handleResponse(BaseRequest request,
								int statusCode, String errorMsg, String response) {
							// TODO Auto-generated method stub
							if (statusCode != 200)
								return;
							else {
								boolean success = false;
								try {
									JSONObject obj = new JSONObject(response);
									success = obj.optBoolean("success", false);
									if (success) {
										final double data = obj.optDouble(
												"data", 0);
										ViewUtils
												.runInMainThread(new Runnable() {

													@Override
													public void run() {
														// TODO Auto-generated
														// method stub
														deliverFeeLabel.setText(String
																.format("¥ %.2f",
																		data));
														discountedPriceLabel.setText(String
																.format("¥ %.2f",
																		totalPrice
																				+ data));
													}
												});
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
						}
					}).start();

		} else {
			userInfoContainer.configurableTextView1.setText("请选择收货地址");
			userInfoContainer.configurableTextView2.setText("");
			deliverFeeLabel.setText(String.format("¥ %.2f", fee));
		}

		if (Config.sharedConfig().payMethods.size() > selectedPayMethod) {
			payMethodContainer.configurableTextView1
					.setText(String.format("支付方式  %s",
							Config.sharedConfig().payMethods
									.get(selectedPayMethod).name));
		}

		totalPriceLabel.setText(String.format("¥ %.2f", totalPrice));
		discountedPriceLabel.setText(String.format("¥ %.2f", totalPrice + fee));

	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return "结算中心";
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == userInfoContainer.container) {
			AddressListFragment fragment = new AddressListFragment();
			fragment.selectMode = true;
			getContainerActivity().addFragment(fragment);
		} else if (v == payMethodContainer.container) {
			new ChoosePayMethodDialog(getActivity())
					.setSelectedIndex(selectedPayMethod)
					.setDelegate(new PickerDialogDelegate() {

						@Override
						public void selectedItemAtIndex(int index) {
							// TODO Auto-generated method stub
							selectedPayMethod = index;
							payMethodContainer.configurableTextView1
									.setText(String.format("支付方式  %s", Config
											.sharedConfig().payMethods
											.get(index).name));
						}

						@Override
						public void didCancel() {
							// TODO Auto-generated method stub

						}
					}).setCustomTitle("支付方式").show();
		} else if (v == confirmButton) {
			if (!verify())
				return;
			showProgressDialog(null, false);
			new CreateOrderRequest()
					.setProductList(orderItems)
					.setShippingID(0)
					.setPayMethod(
							Config.sharedConfig().payMethods
									.get(selectedPayMethod).name)
					.setRemark(DCUser.sharedUser().address.remark)
					.setAddressID(DCUser.sharedUser().address.id)
					.setHandler(new ResponseHandler() {

						@Override
						public void handleResponse(BaseRequest request,
								int statusCode, String errorMsg, String response) {
							OrderFragment.this.dismissProgressDialog();
							if (statusCode == 200) {
								int orderId = -1;
								boolean success = false;
								String errmsg = null;
								try {
									JSONObject object = new JSONObject(response);

									success = object.getBoolean("success");
									errmsg = object.optString("msg", null);
									orderId = object.getInt("data");
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								if (orderId == -1 || !success) {
									String msg = errmsg != null ? errmsg
											: "提交失败";
									ViewUtils.showToast(msg, Toast.LENGTH_LONG);
								} else {
									DaCoolTransactionBill bill = new DaCoolTransactionBill();
									bill.amount = String.format("%.2f",
											totalPrice);
									;
									bill.billId = orderId;
									bill.dateString = DateFormat.format(
											"yyyy-MM-dd ,  hh:mm:ss",
											new Date()).toString();
									bill.status = 0;
									bill.items = orderItems;
									DaCoolHelper.sharedInstance().clearCart();
									// DaCoolHelper.sharedInstance().getMyBills()
									// .add(bill);
									BillListFragment bf = new BillListFragment();
									OrderFragment.this.getContainerActivity()
											.addFragment(bf);
								}

							} else {
								ViewUtils.runInMainThread(new Runnable() {

									@Override
									public void run() {
										// TODO Auto-generated method stub
										Toast.makeText(getActivity(), "通讯失败",
												Toast.LENGTH_LONG).show();
									}
								});
							}

						}
					}).start();

		}

		super.onClick(v);
	}

	private boolean verify() {
		if (DCUser.sharedUser().address == null) {
			Toast.makeText(getActivity(), "请选择收货地址", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}

}
